<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 社群主管理
 */
namespace app\allwin\controller;
use app\allwin\widget\Inform;
use think\facade\Request;
use think\facade\Validate;
use app\common\model\SystemUser;
use app\allwin\model\AllwinUserAgent;
use app\allwin\model\Worker;
use app\allwin\model\StoreWorker;
use app\allwin\model\AllwinStore;
use app\allwin\model\AllwinUser;
use app\allwin\model\Vip;
use think\helper\Time;
use util\Util;

class User extends Common{

    public $mini_program   = []; 

    public function initialize() {
        parent::initialize();
        $this->assign('pathMaps', [['name'=>'社群主管理','url'=>url("user/index")]]);
    }

   /**
     * 社群主管理
     */
    public function index($types = 0){
        $uid   = trim(input('get.uid',''));
        $condition[] = ['member_miniapp_id','=',$this->member_miniapp_id] ;
        $time      = Request::param('time/d',0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['create_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['create_time','<=',strtotime($endtime)];
            }
        }
        if(!empty($uid)){
            $condition[] = ['uid','=',$uid] ;
        }
        $view['pass_num']   = AllwinUserAgent::where($condition)->where(['is_pass' => 0])->count();
        $view['lock_num']   = AllwinUserAgent::where($condition)->where(['is_lock' => 1])->count();
        if($types == 1){
            $condition[] = ['is_lock','=',1];
        }else if($types == 2){
            $condition[] = ['is_pass','=',0];
        }else{
            $condition[] = ['is_pass','=',1];
            $condition[] = ['is_lock','=',0];
        }
        $view['uid']    = $uid;
        $view['types']      = $types;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        $view['time']       = $time;
        $view['worker_num'] = AllwinUserAgent::where($condition)->count();
        $view['sum_price']  = AllwinUserAgent::where($this->mini_program)->where($condition)->sum('price');
        $view['list']       = AllwinUserAgent::where($condition)->where($this->mini_program)->paginate(20);
        return view()->assign($view);
    }
    
   /**
     * 添加社群主
     */
    public function select(){ 
        if(request()->isAjax()){
            $ids = input('post.ids/s');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要添加社群主的用户']);
            }
            $ida = (array)ids($ids,true);
            if(empty($ida)){
                return json(['code'=>0,'msg'=>'请选择要添加社群主的用户']);
            }
            $result = AllwinUserAgent::add($this->member_miniapp_id,$ida);
            if($result){
                return json(['code'=>200,'msg'=>'社群主添加成功','data' =>[]]);
            }else{
                return json(['code'=>0,'msg'=>'社群主添加操作失败']);
            }
        }else{
            $keyword = trim(input('get.keyword','','htmlspecialchars'));
            $condition['is_lock'] = 0;
            $condition['member_miniapp_id'] = $this->member_miniapp_id;
            if(!empty($keyword)){
                $condition['phone_uid'] = $keyword;     
            }
            $view['keyword']   = input('get.keyword');
            $view['list']      = AllwinUserAgent::selects($condition);
            return view()->assign($view);   
        }
    }

    //删除
    public function agentdelete(){
        $id = input('get.id/d');
        $result = AllwinUserAgent::where($this->mini_program)->where(['uid' => $id])->delete();
        if($result){
            AllwinUser::editer($id,0);    //取消店铺关系
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        } 
    }

   /**
     * 员工管理
     */
    public function worker(int $types = 0){
        $uid   = trim(input('get.uid',''));
        $condition[] = ['member_miniapp_id','=',$this->member_miniapp_id] ;
        $time      = Request::param('time/d',0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['create_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['create_time','<=',strtotime($endtime)];
            }
        }
        if(!empty($uid)){
            $condition[] = ['uid','=',$uid] ;
        }
        $view['pass_num']   = Worker::where($condition)->where(['is_pass' => 0])->count();
        $view['lock_num']   = Worker::where($condition)->where(['is_lock' => 1])->count();
        if($types == 1){
            $condition[] = ['is_lock','=',1];
        }else if($types == 2){
            $condition[] = ['is_pass','=',0];
        }else{
            $condition[] = ['is_pass','=',1];
            $condition[] = ['is_lock','=',0];
        }
        $view['uid']    = $uid;
        $view['types']      = $types;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        $view['time']       = $time;
        $view['worker_num'] = Worker::where($condition)->count();
        $view['sum_price']  = Worker::where($this->mini_program)->where($condition)->sum('price');
        $view['list']       = Worker::where($condition)->where($this->mini_program)->paginate(20);
        $view['pathMaps']   = [['name' => ' 合伙人', 'url'=>url("user/worker")]];
        return view()->assign($view);   
    }
 
   /**
     * 选择员工
     */
    public function selectWorker(){ 
        if(request()->isAjax()){
            $ids = input('post.ids/s');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择用户']);
            }
            $ida = (array)ids($ids,true);
            if(empty($ida)){
                return json(['code'=>0,'msg'=>'请选择要添加的合伙人']);
            }
            $result = Worker::add($this->member_miniapp_id,$ida);
            if($result){
                return json(['code'=>302,'msg'=>'公司员工添加成功','data' =>[]]);
            }else{
                return json(['code'=>0,'msg'=>'公司员工添加失败']);
            }
        }else{
            $keyword = trim(input('get.keyword','','htmlspecialchars'));
            $condition[] = ['is_lock','=',0] ;
            $condition[] = ['member_miniapp_id','=',$this->member_miniapp_id] ;
            if(!empty($keyword)){
                if(Validate::isMobile($keyword)){
                    $condition[] = ['phone_uid','=',$keyword] ;
                }else{
                    $condition[] = ['nickname','like','%'.$keyword.'%'];
                }
            }
            $view['keyword']   = input('get.keyword');
            $view['list']      = Worker::selects($condition,$this->member_miniapp_id);
            return view()->assign($view);   
        }
    }

    //删除员工
    public function workerDelete(){
        $id = input('get.id/d');
        $result = Worker::where(['member_miniapp_id' => $this->member_miniapp_id,'id' =>$id])->delete();
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        } 
    }

    //预览用户信息
    public function review(int $uid){
        $view['user']  = SystemUser::where($this->mini_program)->where(['id' => $uid])->find();
        if(empty($view['user'])){
            $this->error('用户不存在');
        }
        $view['store'] = AllwinStore::where($this->mini_program)->where(['manage_uid' => $uid])->select();
        $view['vip']   = Vip::where($this->mini_program)->where(['user_id' => $uid,'is_lock' => 0])->find();
        $worker = Worker::where($this->mini_program)->where(['uid' => $uid])->field('store_ids')->find();
        if(!empty($worker)){
            $view['worker_store'] = AllwinStore::where($this->mini_program)->whereIn('id',$worker->store_ids)->select();
        }
        $view['worker']      = $worker;
        $view['store_worker'] = StoreWorker::where($this->mini_program)->where(['uid' => $uid])->select();
        $view['agent']        = AllwinUserAgent::where($this->mini_program)->where(['uid' => $uid])->count();
        return view()->assign($view);      
    }
    

    //所属店铺
    public function workerStore(int $id){
        $user = Worker::where($this->mini_program)->where(['id' => $id])->find();
        if(empty($user)){
            $this->error('不存在');
        }
        $ids = empty($user->store_ids) ? [] : explode(',',$user->store_ids);
        $view['store'] = AllwinStore::where($this->mini_program)->whereIN('id',$ids)->select();
        $view['worker_id'] = $id; 
        $view['pathMaps'] = [['name'=>'合伙人','url'=>url('user/worker')],['name'=>'所属好店','url'=>'javascript:;']];
        return view()->assign($view);      
    }

    /**
     * 选择所属好店
    */
    public function selectWorkerStore(int $worker_id){
        if(request()->isAjax()){
            $ids = input('post.ids/s');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要关联的商家']);
            }
            $ids = (array)ids($ids,true);
            $user = Worker::where($this->mini_program)->where(['id' => $worker_id])->find();
            if(empty($user)){
                return json(['code'=>0,'msg'=>'资源不存在']);
            }
            $store_ids = empty($user->store_ids) ? [] : explode(',',$user->store_ids);
            $user->store_ids = implode(',',Util::unique_array(array_merge($ids,$store_ids))); 
            $user->save();
            return json(['code'=>200,'msg'=>'操作成功','data' =>[]]);
        }else{
            $keyword = trim(input('get.keyword',''));
            //查询店铺ID
            $worker = Worker::where($this->mini_program)->select();
            $store_id = [];
            foreach ($worker as $value) {
                $ids = empty($value->store_ids) ? [] : explode(',',$value->store_ids);
                $store_id = array_merge($store_id,$ids);
            }            
            $condition = [];
            $condition[] = ['is_lock','=',0];
            if(!empty($keyword)){
                $condition[] = ['name','like','%'.$keyword.'%'];
            }
            $view['lists']     = AllwinStore::where($this->mini_program)->where($condition)->whereNotIn('id',$store_id)->order('is_top desc,sort desc,id desc')->paginate(20);
            $view['keyword']   = $keyword;
            $view['worker_id'] = $worker_id; 
            return view()->assign($view);   
        }
    }

    /**
     * 删除所属好店
    */
    public function workerStoreDelete(int $worker_id,int $store_id){
        $user = Worker::where($this->mini_program)->where(['id' => $worker_id])->find();
        if(empty($user)){
            return json(['code'=>0,'msg'=>'资源不存在']);
        }
        $user->store_ids = ids(array_values_unset($store_id,(array)ids($user->store_ids,true)));
        $user->save();
        return json(['code'=>200,'msg'=>'操作成功']);
    }


    public function isLock(int $id){
        $result = Worker::isLock($id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    }

    public function isPass(int $id){
        $result = Worker::isPass($id,$this->member_miniapp_id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    }
    public function agentLock(int $id){
        $result = AllwinUserAgent::isLock($id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    }

    public function agentPass(int $id){
        $result = AllwinUserAgent::isPass($id,$this->member_miniapp_id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    }
}